<template>
  <el-card shadow="hover" class="monitoring-control">
    <div class="control-header">
      <div class="header-left">
        <h3 class="control-title">实时监控控制</h3>
        <el-badge 
          :value="statusBadgeText" 
          :type="statusBadgeType"
          class="status-badge"
        />
      </div>
      <div class="header-actions">
        <el-button 
          size="small" 
          text 
          :icon="Refresh"
          @click="handleRefreshStatus"
          :loading="refreshing"
        />
      </div>
    </div>
    
    <div class="control-body">
      <div class="status-grid">
        <div class="status-card">
          <div class="status-icon-container">
            <el-icon :class="`status-icon status-${monitoringStatus?.isMonitoring ? 'success' : 'warning'}-icon`">
              <component :is="monitoringStatus?.isMonitoring ? VideoPlay : VideoPause" />
            </el-icon>
          </div>
          <div class="status-info">
            <div class="status-label">监控状态</div>
            <div class="status-value">{{ monitoringStatus?.isMonitoring ? '运行中' : '已停止' }}</div>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-icon-container">
            <el-icon :class="'status-icon status-info-icon'">
              <Timer />
            </el-icon>
          </div>
          <div class="status-info">
            <div class="status-label">采集间隔</div>
            <div class="status-value">{{ monitoringStatus?.intervalTime || '60秒' }}</div>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-icon-container">
            <el-icon :class="'status-icon status-info-icon'">
              <Clock />
            </el-icon>
          </div>
          <div class="status-info">
            <div class="status-label">上次更新</div>
            <div class="status-value">{{ lastUpdateTime ? formatDateTime(lastUpdateTime) : '--' }}</div>
          </div>
        </div>
      </div>
      
      <div class="button-group">
        <el-space :size="'large'" wrap>
          <el-button 
            type="primary" 
            :disabled="monitoringStatus?.isMonitoring || refreshing"
            @click="handleStartMonitoring"
            class="action-btn primary-btn"
          >
            <el-icon><VideoPlay /></el-icon>
            启动监控
          </el-button>
          <el-button 
            type="danger" 
            :disabled="!monitoringStatus?.isMonitoring || refreshing"
            @click="handleStopMonitoring"
            class="action-btn danger-btn"
          >
            <el-icon><VideoPause /></el-icon>
            停止监控
          </el-button>

        </el-space>
      </div>
      
      <div class="logs-section">
        <div class="logs-header">
          <h4 class="logs-title">操作日志</h4>
          <el-button 
            size="small" 
            text 
            @click="clearLogs"
            :disabled="logs.length === 0"
          >
            清空日志
          </el-button>
        </div>
        <el-scrollbar height="200px" class="logs-scrollbar">
          <div class="logs-container">
            <transition-group name="log-fade">
              <div 
                v-for="(log, index) in logs" 
                :key="index" 
                class="log-item"
                :class="log.type ? `log-${log.type}` : 'log-info'"
              >
                <div class="log-badge">
                  <el-icon :size="12">
                    <component :is="getLogIcon(log.type || 'info')" />
                  </el-icon>
                </div>
                <div class="log-content">
                  <div class="log-message">{{ log.content }}</div>
                  <div class="log-time">{{ log.time }}</div>
                </div>
              </div>
            </transition-group>
            <div v-if="logs.length === 0" class="no-logs">
              <el-empty description="暂无操作记录" :image-size="60" />
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Refresh, 
  VideoPlay, 
  VideoPause, 
  Timer, 
  Clock, 
  DataLine,
  CircleCheck,
  CircleClose,
  WarningFilled,
  InfoFilled
} from '@element-plus/icons-vue';
import networkService from '../api/networkService.js';

const emit = defineEmits(['monitoring-status-change', 'mock-data-generated', 'refresh-data']);

// 响应式数据
const monitoringStatus = ref(null);
const lastUpdateTime = ref(null);
const logs = ref([]);
const refreshing = ref(false);

// 计算状态徽章
const statusBadgeText = computed(() => {
  return monitoringStatus.value?.isMonitoring ? '运行中' : '已停止';
});

const statusBadgeType = computed(() => {
  return monitoringStatus.value?.isMonitoring ? 'success' : 'warning';
});

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
};

// 添加日志
const addLog = (content, type = 'info') => {
  logs.value.unshift({
    time: formatDateTime(new Date()),
    content,
    type
  });
  // 只保留最近10条日志
  if (logs.value.length > 20) {
    logs.value = logs.value.slice(0, 20);
  }
};

// 获取日志类型对应的图标
const getLogIcon = (type) => {
  switch (type) {
    case 'success':
      return CircleCheck;
    case 'error':
      return CircleClose;
    case 'warning':
      return WarningFilled;
    case 'info':
    default:
      return InfoFilled;
  }
};

// 获取监控状态
const fetchMonitoringStatus = async () => {
  try {
    const response = await networkService.getMonitoringStatus();
    if (response.success) {
      monitoringStatus.value = response.data;
      lastUpdateTime.value = new Date();
    }
  } catch (error) {
    ElMessage.error('获取监控状态失败');
    addLog('获取监控状态失败', 'error');
  }
};

// 处理刷新状态
const handleRefreshStatus = async () => {
  try {
    refreshing.value = true;
    await fetchMonitoringStatus();
    addLog('刷新监控状态', 'info');
  } finally {
    refreshing.value = false;
  }
};

// 启动监控
const handleStartMonitoring = async () => {
  try {
    refreshing.value = true;
    const response = await networkService.startMonitoring();
    if (response.success) {
      ElMessage.success(response.message || '启动监控成功');
      addLog('实时监控已启动', 'success');
      await fetchMonitoringStatus();
      emit('monitoring-status-change', true);
      emit('refresh-data');
    }
  } catch (error) {
    ElMessage.error('启动监控失败');
    addLog('启动监控失败', 'error');
  } finally {
    refreshing.value = false;
  }
};

// 停止监控
const handleStopMonitoring = async () => {
  try {
    refreshing.value = true;
    const response = await networkService.stopMonitoring();
    if (response.success) {
      ElMessage.success(response.message || '停止监控成功');
      addLog('实时监控已停止', 'info');
      await fetchMonitoringStatus();
      emit('monitoring-status-change', false);
    }
  } catch (error) {
    ElMessage.error('停止监控失败');
    addLog('停止监控失败', 'error');
  } finally {
    refreshing.value = false;
  }
};

// 生成模拟数据
const handleGenerateMockData = async () => {
  try {
    refreshing.value = true;
    const response = await networkService.generateMockData();
    if (response.success) {
      ElMessage.success(response.message || '生成模拟数据成功');
      addLog('模拟数据生成成功', 'success');
      emit('mock-data-generated');
      emit('refresh-data');
    }
  } catch (error) {
    ElMessage.error('生成模拟数据失败');
    addLog('生成模拟数据失败', 'error');
  } finally {
    refreshing.value = false;
  }
};

// 清空日志
const clearLogs = () => {
  logs.value = [];
  addLog('日志已清空', 'info');
};

// 组件挂载时获取状态
onMounted(() => {
  fetchMonitoringStatus();
  addLog('组件已加载', 'info');
});
</script>

<style scoped>
.monitoring-control {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  background: white;
  overflow: hidden;
}

.monitoring-control:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.control-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.status-badge {
  transform: translateY(-2px);
}

.control-body {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}

.status-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.status-card:hover {
  background: #f0f2f5;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.status-icon-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
}

.status-icon {
  font-size: 24px;
  transition: transform 0.3s ease;
}

.status-card:hover .status-icon {
  transform: scale(1.1);
}

.status-success-icon {
  color: #67c23a;
}

.status-warning-icon {
  color: #e6a23c;
}

.status-info-icon {
  color: #409eff;
}

.status-info {
  flex: 1;
}

.status-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
  font-weight: 500;
}

.status-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
}

.button-group {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}

.action-btn {
  transition: all 0.3s ease;
  border-radius: 6px;
  font-weight: 500;
  min-width: 120px;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.primary-btn:hover {
  background-color: #66b1ff;
}

.danger-btn:hover {
  background-color: #f78989;
}

.success-btn:hover {
  background-color: #85ce61;
}

.logs-section {
  margin-top: 8px;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 4px;
}

.logs-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.logs-scrollbar {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fafafa;
}

.logs-container {
  padding: 8px;
  min-height: 120px;
}

.log-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 6px;
  background: white;
  transition: all 0.3s ease;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

.log-item:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.log-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  background: #f5f7fa;
  flex-shrink: 0;
  margin-top: 2px;
}

.log-content {
  flex: 1;
}

.log-message {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
  word-break: break-word;
  font-weight: 500;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-info .log-badge {
  background: #ecf5ff;
}

.log-info .log-badge .el-icon {
  color: #409eff;
}

.log-success .log-badge {
  background: #f0f9ff;
}

.log-success .log-badge .el-icon {
  color: #67c23a;
}

.log-warning .log-badge {
  background: #fdf6ec;
}

.log-warning .log-badge .el-icon {
  color: #e6a23c;
}

.log-error .log-badge {
  background: #fef0f0;
}

.log-error .log-badge .el-icon {
  color: #f56c6c;
}

.no-logs {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 120px;
}

/* 日志动画 */
.log-fade-enter-active,
.log-fade-leave-active {
  transition: all 0.5s ease;
}

.log-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.log-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .monitoring-control {
    border-radius: 8px;
  }
  
  .status-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .control-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 20px;
  }
  
  .logs-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .log-item {
    padding: 10px;
  }
  
  .log-message {
    font-size: 13px;
  }
  
  .action-btn {
    min-width: 100px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .status-card {
    padding: 12px;
  }
  
  .status-icon-container {
    width: 40px;
    height: 40px;
  }
  
  .status-icon {
    font-size: 20px;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>